package com.camera.yl.manager

import android.content.Context
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.camera.base.Log.YLogImpl
import com.camera.yl.models.UploadInfo
import com.camera.yl.models.UploadStatus
import com.camera.yl.service.UploadService
import java.util.concurrent.ConcurrentHashMap

/**
 * 上传管理器单例
 * 负责管理上传状态、进度和与UI的通信
 */
object UploadManager {
    private val TAG = "UploadManager"
    
    // 上传状态映射 filePath -> UploadInfo
    private val uploadStatusMap = ConcurrentHashMap<String, UploadInfo>()
    
    // 上传状态变化的LiveData
    private val _uploadStatusLiveData = MutableLiveData<Map<String, UploadInfo>>()
    val uploadStatusLiveData: LiveData<Map<String, UploadInfo>> = _uploadStatusLiveData
    
    // 防重复调用：记录最后一次上传请求的时间和文件列表
    private var lastUploadTime = 0L
    private var lastUploadFiles: List<String> = emptyList()
    private const val DUPLICATE_CALL_THRESHOLD = 1000L // 1秒内的重复调用被认为是重复
    
    /**
     * 开始上传选中的文件
     */
    fun startUpload(context: Context, filePaths: List<String>) {
        val currentTime = System.currentTimeMillis()
        
        // 检查是否为重复调用
        if (currentTime - lastUploadTime < DUPLICATE_CALL_THRESHOLD && 
            filePaths == lastUploadFiles) {
            YLogImpl.w(TAG, "检测到重复上传调用，忽略此次请求")
            return
        }
        
        // 更新最后一次调用记录
        lastUploadTime = currentTime
        lastUploadFiles = filePaths.toList()
        
        YLogImpl.i(TAG, "开始上传文件，共${filePaths.size}个文件")
        
        // 初始化上传状态为等待中
        filePaths.forEach { filePath ->
            updateUploadStatus(filePath, UploadStatus.PENDING, 0)
        }
        
        // 启动上传服务
        val intent = Intent(context, UploadService::class.java)
        intent.putStringArrayListExtra("file_paths", ArrayList(filePaths))
        context.startForegroundService(intent)
    }
    
    /**
     * 更新上传状态
     */
    fun updateUploadStatus(filePath: String, status: UploadStatus, progress: Int = 0, errorMessage: String? = null) {
        if (status == UploadStatus.SUCCESS || status == UploadStatus.FAILED) {
            // 上传完成（成功或失败）后从状态映射中移除
            // 这样可以隐藏进度条，并触发UI重新绑定显示已上传标志
            uploadStatusMap.remove(filePath)
            YLogImpl.d(TAG, "上传完成，移除状态: $filePath, 最终状态: $status, 进度: $progress%")
        } else {
            // 其他状态（PENDING, UPLOADING）正常更新
            val uploadInfo = UploadInfo(filePath, status, progress, errorMessage)
            uploadStatusMap[filePath] = uploadInfo
            YLogImpl.d(TAG, "更新上传状态: $filePath, 状态: $status, 进度: $progress%")
        }
        
        // 通知UI更新
        _uploadStatusLiveData.postValue(uploadStatusMap.toMap())
    }
    
    /**
     * 获取文件上传状态
     */
    fun getUploadStatus(filePath: String): UploadInfo? {
        return uploadStatusMap[filePath]
    }
    
    /**
     * 获取文件上传进度
     */
    fun getUploadProgress(filePath: String): Int {
        return uploadStatusMap[filePath]?.progress ?: 0
    }
    
    /**
     * 检查文件是否正在上传
     */
    fun isUploading(filePath: String): Boolean {
        return uploadStatusMap[filePath]?.status == UploadStatus.UPLOADING
    }
    
    /**
     * 检查文件是否在上传队列中
     */
    fun isInUploadQueue(filePath: String): Boolean {
        val status = uploadStatusMap[filePath]?.status
        return status == UploadStatus.PENDING || status == UploadStatus.UPLOADING
    }
    
    /**
     * 移除上传状态（上传完成后清理）
     */
    fun removeUploadStatus(filePath: String) {
        uploadStatusMap.remove(filePath)
        _uploadStatusLiveData.postValue(uploadStatusMap.toMap())
        YLogImpl.d(TAG, "移除上传状态: $filePath")
    }
    
    /**
     * 清空所有上传状态
     */
    fun clearAllUploadStatus() {
        uploadStatusMap.clear()
        _uploadStatusLiveData.postValue(emptyMap())
        YLogImpl.d(TAG, "清空所有上传状态")
    }
    
    /**
     * 获取等待上传的文件列表
     */
    fun getPendingUploads(): List<String> {
        return uploadStatusMap.filter { it.value.status == UploadStatus.PENDING }
            .keys.toList()
    }
    
    /**
     * 获取正在上传的文件列表
     */
    fun getUploadingFiles(): List<String> {
        return uploadStatusMap.filter { it.value.status == UploadStatus.UPLOADING }
            .keys.toList()
    }
} 